//
//  CZEmoticonInputView.swift
//  表情键盘
//
//  Created by ffxk007 on 2017/7/10.
//  Copyright © 2017年 ffxk007. All rights reserved.
//

import UIKit

///可重用的表示服
fileprivate let cellID = "cellID"
///表情输入视图
class CZEmoticonInputView: UIView {

    @IBOutlet weak var toolBar: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    ///选中表情回调闭包属性
    fileprivate var selectedEmotiocnCallBack:((_ emoticon:CZEmoticon?)->())?
    
    ///加载并且返回输入视图
    class func inputView(selectedEmoticon:@escaping (_ emoticon:CZEmoticon?
        )->()) -> CZEmoticonInputView {
        let nib =  UINib(nibName: "CZEmoticonInputV", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! CZEmoticonInputView
        
        //记录闭包
        v.selectedEmotiocnCallBack = selectedEmoticon
        
        return v
    }
    
    override func awakeFromNib() {
        //注册可重用cell
        collectionView.register(CZEmoticonCell.self, forCellWithReuseIdentifier: cellID)
    }
}

extension CZEmoticonInputView:UICollectionViewDataSource {
    //分组数量-返回表情包的数量
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return CZEmoticonManager.shared.packages.count
    }
    // 返回每个分组中的表情'页'的数量
    // 每个分组的表情包中，表情页面的数量emoticons 数组 / 20
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonManager.shared.packages[section].numberOfPages
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //1.取cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CZEmoticonCell
        //2.设置dell-传递对应页面的表情数组
        cell.emoticons = CZEmoticonManager.shared.packages[indexPath.section].emoticon(page: indexPath.item)
        
        ///设置代理
        cell.delegate = self
        
        //3.返回cell
        return cell
    }
}

// MARK: - CZEmoticonCellDelegate
extension CZEmoticonInputView:CZEmoticonCellDelegate {
    func emoticonCellDidSelectedEmoticon(cell: CZEmoticonCell, em: CZEmoticon?) {
//        print(em as Any)
        
        //执行闭包回调选中的表情
        selectedEmotiocnCallBack?(em)
        
    }
}
